package fun.flyee.android.pengshan.api;

import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.util.Log;
import android.webkit.JavascriptInterface;

import com.amap.api.location.AMapLocationClient;
import com.amap.api.track.AMapTrackClient;
import com.amap.api.track.query.model.HistoryTrackRequest;
import com.hcvsa.MyHCVSA;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;

import fun.flyee.android.pengshan.AppContex;
import fun.flyee.android.pengshan.Constant;
import fun.flyee.android.pengshan.Storage;
import fun.flyee.android.pengshan.acts.Router;
import fun.flyee.android.pengshan.acts.helper.ServiceHelper;
import fun.flyee.android.pengshan.events.AuthEvent;
import fun.flyee.android.pengshan.events.LatLngEvent;
import fun.flyee.android.pengshan.events.UnauthEvent;
import fun.flyee.android.pengshan.events.WebEvent;
import fun.flyee.android.pengshan.fgts.WebFragment;
import fun.flyee.android.pengshan.utils.GeoUtil;
import fun.flyee.android.pengshan.utils.Logger;
import fun.flyee.android.pengshan.utils.Systems;
import fun.flyee.android.pengshan.utils.Util;
import hcvs.hcvsa.HCVSA;

import static android.app.Activity.RESULT_OK;

public class JsBridge {

    private WebFragment webFragment;

    private String payload;

    private AMapLocationClient locClient;

    public JsBridge(WebFragment webFragment, String payload) {
        this.webFragment = webFragment;
        this.payload = payload;
    }

    @JavascriptInterface
    public String getApiUrl() {
        return Constant.apiUrl();
    }

    @JavascriptInterface
    public String getUserToken() {
        return Storage.get(Storage.TOKEN);
    }

    @JavascriptInterface
    public String getPayload() {
        return payload;
    }

    @JavascriptInterface
    public void reload() {
        webFragment.getActivity().runOnUiThread(() -> webFragment.mWebView.reload());
    }

    @JavascriptInterface
    public void forResult(String path, String payload) {
        if (webFragment.getActivity() == null) return;
        webFragment.getActivity().runOnUiThread(() -> Router.forResult(webFragment.getActivity(), path, payload));
    }

    @JavascriptInterface
    public void withPayload(String path, String payload) {
        if (webFragment.getActivity() == null) return;
        webFragment.getActivity().runOnUiThread(() -> Router.withPayload(webFragment.getActivity(), path, payload));
    }

    @JavascriptInterface
    public void returnResult(String data) {
        Intent intent = new Intent();
        intent.putExtra("data", data);
        webFragment.getActivity().setResult(RESULT_OK, intent);
        webFragment.getActivity().finish();
    }

    @JavascriptInterface
    public void emitEvent(String name, String payload) {
        if (webFragment.getActivity() == null) return;
        webFragment.getActivity().runOnUiThread(() -> EventBus.getDefault().post(new WebEvent(name, payload)));
    }

    @JavascriptInterface
    public void callPhone(String number) {
        if (webFragment.getActivity() == null) return;
        webFragment.getActivity().runOnUiThread(() -> {
            if (Systems.requestCallPermission(webFragment.getActivity())) {
                Systems.callPhone(webFragment.getContext(), number);
            }
        });
    }

    @JavascriptInterface
    public void takePhoto(int max) {
        if (max > 0) {
            Router.photo(webFragment.getActivity(), max);
        }
    }

    @JavascriptInterface
    public void pickVideo() {
        Router.video(webFragment.getActivity());
    }

    @JavascriptInterface
    public void scanQRCode() {
        Router.scanQRCode(webFragment.getActivity());
    }

    @JavascriptInterface
    public void uploadPhoto(int max) {
        if (max > 0) {
            Router.upload(webFragment.getActivity(), max);
        }
    }

    @JavascriptInterface
    public void go(String path, String query) {
        Router.go(webFragment.getContext(), path, query);
    }

    @JavascriptInterface
    public void jump(String url) {
        Router.jump(webFragment.getContext(), url);
    }

    @JavascriptInterface
    public void unauth() {
        try {
            MyHCVSA.getInstance().Logout();
        } catch (Exception e) {
            Logger.e("HC video logout error", e);
        }
        Storage.clear();
        if (webFragment != null) {
            Router.login(webFragment.getContext());
        }
        EventBus.getDefault().post(new UnauthEvent());
    }

    @JavascriptInterface
    public String getOnlineStatus() {
        return MyHCVSA.getLoginStatus() + "";
    }

    @JavascriptInterface
    public void auth() {
        EventBus.getDefault().post(new AuthEvent());
    }

    @JavascriptInterface
    public void goBack() {
        webFragment.getActivity().finish();
    }

    @JavascriptInterface
    public void location() {
        Router.location(webFragment.getActivity());
    }

    @JavascriptInterface
    public void currentLocation() {
        webFragment.getActivity().runOnUiThread(() -> {
            if (webFragment.getActivity() == null || webFragment.getActivity().isDestroyed())
                return;
            locClient = GeoUtil.getLocation((lat, lng) -> callJs("onLocation", lat, lng));
        });
    }

    @JavascriptInterface
    public void stopLocation() {
        if (locClient != null) {
            if (locClient.isStarted()) {
                locClient.stopLocation();
            }
            locClient = null;
        }
    }

    @JavascriptInterface
    public void navigate(Double lat, Double lng) {
        Router.navigate(webFragment.getContext(), lat, lng);
    }

    @JavascriptInterface
    public void currentLatLng() {
        EventBus.getDefault().post(new LatLngEvent());
    }

    @JavascriptInterface
    public void exit() {
        Storage.del(Storage.TOKEN);
        EventBus.getDefault().post(new UnauthEvent());
    }

    @JavascriptInterface
    public void confirmLocationAddr(double lat, double lng, String addr) {
        Intent intent = new Intent();
        intent.putExtra("lat", lat);
        intent.putExtra("lng", lng);
        intent.putExtra("addr", addr);
        webFragment.getActivity().setResult(RESULT_OK, intent);
        webFragment.getActivity().finish();
    }

    @JavascriptInterface
    public void setStore(String key, String value) {
        Storage.set(key, value);
    }

    @JavascriptInterface
    public String getStore(String key) {
        return Storage.get(key);
    }

    @JavascriptInterface
    public void delStore(String key) {
        Storage.del(key);
    }

    @JavascriptInterface
    public void setGlobal(String key, String value) {
        Storage.set2(key, value);
    }

    @JavascriptInterface
    public String getGlobal(String key) {
        return Storage.get2(key);
    }

    @JavascriptInterface
    public void delGlobal(String key) {
        Storage.del2(key);
    }

    @JavascriptInterface
    public void download(String name, String url) {
        if (webFragment.getActivity() != null && !webFragment.getActivity().isDestroyed()) {
            webFragment.getActivity().runOnUiThread(() -> {
                Log.i("download: ", name + " | " + url);
                Systems.downloadFile(webFragment.getContext(), name, url);
            });
        }
    }

    @JavascriptInterface
    public void playMonitor(String channelId) {
        if (webFragment.getActivity() != null && !webFragment.getActivity().isDestroyed()) {
            webFragment.getActivity().runOnUiThread(() -> {
                Router.playMonitor(webFragment.getActivity(), channelId);
            });
        }
    }

    @JavascriptInterface
    public void playVideo(String url) {
        if (webFragment.getActivity() != null && !webFragment.getActivity().isDestroyed()) {
            webFragment.getActivity().runOnUiThread(() -> {
                Intent intent = new Intent(Intent.ACTION_VIEW);
                String type = "video/* ";
                Uri uri = Uri.parse(url);
                intent.setDataAndType(uri, type);
                webFragment.getActivity().startActivity(intent);
            });
        }
    }

    @JavascriptInterface
    public void getConferences() {
        if (webFragment != null && webFragment.getActivity() != null) {
            ServiceHelper.getInstance(webFragment.getActivity()).getConferenceList();
        }
    }

    @JavascriptInterface
    public void joinConference(int id) {
        if (webFragment.getActivity() != null && !webFragment.getActivity().isDestroyed()) {
            webFragment.getActivity().runOnUiThread(() -> {
                Router.joinConference(webFragment.getActivity(), id, "");
            });
        }
    }

    public void destroy() {
        if (locClient != null) {
            if (locClient.isStarted()) {
                locClient.stopLocation();
            }
            locClient = null;
        }
        webFragment = null;
    }

    public void callJs(String method, Object... args) {
        if (webFragment.getActivity() != null && webFragment.mWebView != null && webFragment.getActivity().isDestroyed())
            return;
        String js = method + "(%s)";
        String arg = "";
        if (args != null && args.length > 0) {
            List<String> ar = new ArrayList<>();
            for (Object obj : args) {
                if (obj instanceof String) {
                    ar.add(obj.toString());
                } else {
                    ar.add(obj + "");
                }
            }
            arg = Util.join(ar, ",");
        }
        js = String.format(js, arg);
        String function = js;
        if (webFragment.getActivity() != null && !webFragment.getActivity().isDestroyed()) {
            webFragment.getActivity().runOnUiThread(() -> {
                if (webFragment.getActivity() == null || webFragment.mWebView == null) return;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                    webFragment.mWebView.evaluateJavascript("javascript:" + function, value -> Logger.i("webreturn", value));
                } else {
                    webFragment.mWebView.loadUrl("javascript:" + function);
                }
            });
        }
    }
}
